package cn.cyh.product.controller;

import cn.cyh.basic.uitls.AJaxResult;
import cn.cyh.basic.uitls.PageList;
import cn.cyh.product.domain.Product;
import cn.cyh.product.query.ProductQuery;
import cn.cyh.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController  {
    @Autowired
    private IProductService productService;

    @PostMapping
    public PageList<Product> list(@RequestBody ProductQuery query){
        return productService.queryPage(query);
    }

    /**
     * 批量上架
     * @param ids
     * @return
     */
    // onSale
    @PostMapping("/onSale")
    public AJaxResult onSale(@RequestBody List<Long> ids){
        try {
            productService.onSale(ids);
            return AJaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg("操作失败了");
        }
    }

    /**
     * 批量下架
     * @param ids
     * @return
     */
    // offSale
    @PostMapping("/offSale")
    public AJaxResult offSale(@RequestBody List<Long> ids){
        try {
            productService.offSale(ids);
            return AJaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg("操作失败了");
        }
    }

    @PutMapping
    public AJaxResult saveAndUpdate(@RequestBody Product product){
        try {
            if (product.getId() != null){ // 如果有就是修改
                productService.update(product);
                return AJaxResult.myself();
            } else {// 添加
                productService.save(product);
                return AJaxResult.myself();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg(e.getMessage());
        }
    }
    @GetMapping("/{id}")
    public Product queryById(@PathVariable("id") Long id){
        return productService.loadById(id);
    }
}
